// signature
import md5 from "js-md5";

export function signature(data: any, url: string, secret: string): object {
  // 参数签名 密钥 + 时间戳 + header参数 + url
  // 时间戳
  const timestamp = new Date().getTime();
  const nonceStr: string = randomString(8);
  // post参数
  const dataStr = dataSerialize(dataSort(data));
  // 生成签名
  const str =
    dataStr +
    "noncestr=" +
    nonceStr +
    "secret=" +
    secret +
    "&timestamp=" +
    timestamp +
    "&url=" +
    url;
  const sign = md5.md5(str);

  return {
    signature: sign.toUpperCase(), // 将签名字母转为大写
    timestamp,
    secret,
  };
}

// 参数排序
function dataSort(obj: any): object {
  if (JSON.stringify(obj) == "{}" || obj == null) {
    return {};
  }
  return Object.keys(obj)?.sort();
}

// 参数序列化
function dataSerialize(sortObj: any): string {
  let strJoin = "";
  for (const key in sortObj) {
    strJoin += key + "=" + sortObj[key] + "&";
  }
  // return strJoin.substring(0, strJoin.length - 1)
  return strJoin;
}

function randomString(length: number): string {
  let result = "";
  const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  const charactersLength = characters.length;
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}
